package project

import (
	"fmt"
	"github.com/hashicorp/go-memdb"
)

// Person Create a sample struct
type Person struct {
	Email string
	Name  string
	Age   int
}

// Create the DB schema
func CreateDB() {
	schema := &memdb.DBSchema{
		Tables: map[string]*memdb.TableSchema{
			"person": &memdb.TableSchema{
				Name: "person",
				Indexes: map[string]*memdb.IndexSchema{
					"id": &memdb.IndexSchema{
						Name:    "id",
						Unique:  true,
						Indexer: &memdb.StringFieldIndex{Field: "Email"},
					},
					"age": &memdb.IndexSchema{
						Name:    "age",
						Unique:  false,
						Indexer: &memdb.IntFieldIndex{Field: "Age"},
					},
				},
			},
		},
	}

	db, err := memdb.NewMemDB(schema)
	if err != nil {

	}

	// create a new transaction
	txnForWrite := db.Txn(true)

	// insert some people
	people := []*Person{
		&Person{"joe@aol.com", "Joe", 30},
		&Person{"lucy@aol.com", "Lucy", 35},
		&Person{"tariq@aol.com", "Tariq", 21},
		&Person{"dorothy@aol.com", "Dorothy", 53},
	}
	for _, person := range people {
		if insertErr := txnForWrite.Insert("person", person); insertErr != nil {

		}
	}

	// commit the transaction
	txnForWrite.Commit()

	// create read-only transaction
	txnForRead := db.Txn(false)
	defer txnForRead.Abort()

	// lookup by email
	first, readErr := txnForRead.First("person", "id", "joe@aol.com")
	if readErr != nil {

	}
	// print person info
	fmt.Printf("This is : %v, my email is : %v, my age is : %v . \n", first.(*Person).Name, first.(*Person).Email, first.(*Person).Age)

	// list all of people
	allPeople, readAllErr := txnForRead.Get("person", "id")
	if readAllErr != nil {

	}
	for next := allPeople.Next(); next != nil; next = allPeople.Next() {
		person := next.(*Person)
		fmt.Printf("Name is : %v \n", person.Name)
	}

}
